from sqlalchemy import inspect, Column, Integer, String, SmallInteger, orm
from werkzeug.security import generate_password_hash, check_password_hash

from app.libs.error_code import NotFound, AuthFailed
from app.models.base import Base, db, MixinJSONSerializer
import datetime

class User(Base):
    id = Column(Integer, primary_key=True)
    username = Column(String(40), default='')
    openid = Column(String(60), default='',unique=True, nullable=False)
    nickname = Column(String(24), default='')
    avatar = Column(String(120), default='')
    phone = Column(String(11), default='')
    sex = Column(SmallInteger, default=1)
    email = Column(String(24), default='')
    address = Column(String(120), default='')
    auth = Column(SmallInteger, default=1)
    _password = Column('password', String(100))

    def keys(self):
        return ['id', 'username','openid', 'avatar','nickname', 'auth']

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    @staticmethod
    def register_by_openid(nickname, openid, avatar):
        with db.auto_commit():
            user = User()
            user.nickname = nickname
            user.openid = openid
            user.avatar = avatar
            db.session.add(user)

    @staticmethod
    def verify(openid):
        user = User.query.filter_by(openid=openid).first_or_404()
        # if not user.check_password(password):
        #     raise AuthFailed()
        scope = 'AdminScope' if user.auth == 2 else 'UserScope'
        return {'uid': user.id, 'scope': scope}

    def check_password(self, raw):
        if not self._password:
            return False
        return check_password_hash(self._password, raw)

    # def _set_fields(self):
    #     # self._exclude = ['_password']
    #     self._fields = ['_password', 'nickname']
